<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb5">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
               class="el-form-search">
        <el-form-item label="年龄" prop="age" class="el-form-search-item">
          <el-input
            v-model="queryParams.age"
            placeholder="请输入年龄"
            @input="checkPositiveInteger(queryParams.age, 'age')"
            clearable
            size="mini"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="任职医院" prop="authorizedHospital" class="el-form-search-item">
          <el-input
            v-model="queryParams.authorizedHospital"
            placeholder="请输入任职医院"
            clearable
            size="mini"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="nickName" class="el-form-search-item">
          <el-input
            v-model="queryParams.nickName"
            placeholder="请输入姓名"
            clearable
            size="mini"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户性别" prop="sex" class="el-form-search-item">
          <el-select v-model="queryParams.sex" placeholder="请选择用户性别" clearable size="mini">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber" class="el-form-search-item">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号"
            @input="checkPositiveInteger(queryParams.phonenumber, 'phonenumber')"
            clearable
            size="mini"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-table ref="list" :height="tableHeight" v-loading="loading" :data="userList">
      <el-table-column label="姓名" align="center" prop="nickName"/>
      <el-table-column label="用户性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age"/>
      <el-table-column label="手机号码" align="center" prop="phonenumber"/>
      <el-table-column label="任职医院" align="center" prop="authorizedHospital"/>
      <el-table-column
        label="状态"
        align="center"
        key="status"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleUpdate(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deyu:doctor:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false"
               v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addUser, delUser, getUser, listUser, updateUser} from "@/api/deyu/doctor";

export default {
  name: "DeyuDoctor",
  dicts: ['sys_user_sex'],
  data() {
    return {
      // 表格高度
      tableHeight: document.documentElement.clientHeight - 180,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: "u.create_time",
        isAsc: "desc",
        birthDate: null,
        dialysisStartDate: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.queryParams.deptId = this.$route.params && this.$route.params.deptId;
    if (this.queryParams.deptId){
      this.showSearch = false;
    }
    this.getList();
  },
  methods: {
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        deptId: null,
        userName: null,
        nickName: null,
        userType: null,
        email: null,
        phonenumber: null,
        sex: null,
        avatar: null,
        password: null,
        status: "0",
        delFlag: null,
        loginIp: null,
        loginDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        birthDate: null,
        dialysisStartDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 单击行选中数据
    handleRowClick(row, column, event) {
      this.$refs.list.toggleRowSelection(row);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let text = row.status === "0" ? "解冻" : "冻结";
      this.$modal
        .confirm('确认要"' + text + '""' + row.nickName + '"医护账户吗？')
        .then(function () {
          return updateUser(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除记录？').then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    checkPositiveInteger(value, fieldName) {
      // 正则表达式：确保输入的是正整数，不允许负号
      let regex = /^[0-9]\d*$/;
      if (fieldName === 'age') {
        regex = /^[1-9]\d*$/;
      }
      if (value === '' || regex.test(value)) {
        this.queryParams[fieldName] = value;  // 使用传入的字段名动态设置值
      } else {
        this.queryParams[fieldName] = '';  // 如果不符合要求，清空对应字段的值
        this.$message.error('请输入正确的查询参数');
      }
    }
  }
};
</script>
